package com.miplus.ccrm.report.service.cti;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.miplus.ccrm.common.CmdResVo;
import com.miplus.ccrm.common.JPubUtils;
import com.miplus.ccrm.common.JSysUser;
import com.miplus.ccrm.common.JUsrPerm;
import com.miplus.ccrm.report.controller.vo.cti.CallReqVo;
import com.miplus.ccrm.report.controller.vo.cti.CallResvo;
import com.miplus.ccrm.report.controller.vo.cti.DialogueResVo;
import com.miplus.ccrm.report.feign.FiImpAddVo;
import com.miplus.ccrm.report.feign.ICoreFeign;
import com.miplus.ccrm.report.pojo.CtiCallhist;
import com.miplus.ccrm.report.pojo.ReportCallHist;
import com.miplus.ccrm.report.pojo.TRecorder;
import com.miplus.ccrm.report.mapper.TRecorderMapper;
import com.miplus.ccrm.report.service.ExportService;
import com.miplus.ccrm.report.utils.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author pc
 * @description 针对表【t_recorder】的数据库操作Service实现
 * @createDate 2024-07-29 14:33:48
 */
@Slf4j
@Service
public class TRecorderServiceImpl extends MPJBaseServiceImpl<TRecorderMapper, TRecorder>
        implements TRecorderService{

    @Resource
    private ExportService exportService;
    @Resource
    private ICoreFeign iCoreFeign;

    //录音列表
    @Override
    public IPage<CallResvo> recordList(JSysUser user, CallReqVo paras)
    {
        String $usrid=user.getUsrid();
        String phnstar= JUsrPerm.getPermission(user, JUsrPerm.DISSTAR_PHN);
        //2025-05-13
        boolean viewAllCase=JUsrPerm.viewAllFiCase(user);
        boolean viewGrpFiCase = false;
        if(!viewAllCase && user.getMgrgrplist().size()>0)
            viewGrpFiCase = true;

        //2024-08 add Recupload
        return selectJoinListPage(new Page<>(paras.getPageNum(), paras.getPageSize()),
                CallResvo.class,
                new MPJLambdaWrapper<TRecorder>()
                        .selectAs(TRecorder::getRecorderid,CallResvo::getUcallid)
                        .selectAs(TRecorder::getStarttime,CallResvo::getCrdt)
                        .selectAs(TRecorder::getAgentid,CallResvo::getUsrid)
                        .selectAs(TRecorder::getChanneldn,CallResvo::getDn)
                        .selectAs(TRecorder::getInfoid,CallResvo::getRecordurl)
                        .selectAs(ReportCallHist::getTalkspan,CallResvo::getActivespan)
                        .selectAs(ReportCallHist::getWaitspan,CallResvo::getRingspan)
                        .selectAs(TRecorder::getInfodepart,CallResvo::getRecupload)
                        .selectAs("fun_getnames('CTI.CALLTYPE',t.calltype)",CallResvo::getCalltype)
                        .selectAs("fun_getnames('CTI.CALLRESULT',h.callresult)",CallResvo::getCallresult)
                        .selectAs(String.format("fi_starSecu('%s','%s',t.telno,'%s')",$usrid,JUsrPerm.DISSTAR_PHN,phnstar),CallResvo::getAni)
                        .selectAs(String.format("fi_starSecu('%s','%s',t.teldnis,'%s')",$usrid,JUsrPerm.DISSTAR_PHN,phnstar),CallResvo::getDnis)
                        .selectAs("fun_getgrpname(t.agentid)",CallResvo::getGrpname)
                        .selectAs("su.name",CallResvo::getUsrname)
                        .select(TRecorder::getCallid,TRecorder::getTaskflag,TRecorder::getUpasrdt)
                        .innerJoin(ReportCallHist.class,"h",ReportCallHist::getCallmanagenumber,TRecorder::getCallid)
                        .innerJoin("sys_user su on su.usrid = t.agentid")
                        .in(viewGrpFiCase,"su.groups",user.getMgrgrplist())
                        .eq(!viewAllCase && !viewGrpFiCase,TRecorder::getAgentid,$usrid)
                        .eq(ReportCallHist::getDevtype,"device")
                        .notIn(TRecorder::getAgentid,"ivr","qm")
                        .eq(JPubUtils.IsNotEmpty(paras.getUsrid()),TRecorder::getAgentid,paras.getUsrid())
                        .eq(JPubUtils.IsNotEmpty(paras.getCalltype()),TRecorder::getCalltype,paras.getCalltype())
                        .eq(JPubUtils.IsNotEmpty(paras.getCallresult()),ReportCallHist::getCallresult,paras.getCallresult())
                        .eq(JPubUtils.IsNotEmpty(paras.getDn()),TRecorder::getChanneldn,paras.getDn())
                        .between(JPubUtils.IsNotEmpty(paras.getStartdt()), TRecorder::getStarttime,JPubUtils.StringToDate(paras.getStartdt()),JPubUtils.StringToDate(paras.getEnddt()))
                        .ge(JPubUtils.IsNotEmpty(paras.getTalkspan1()),ReportCallHist::getTalkspan,paras.getTalkspan1())
                        .le(JPubUtils.IsNotEmpty(paras.getTalkspan2()),ReportCallHist::getTalkspan,paras.getTalkspan2())
                        .apply(JPubUtils.IsNotEmpty(paras.getPhone()),"(t.telno={0} or t.teldnis={0})",paras.getPhone())
                        .apply(JPubUtils.IsNotEmpty(paras.getGrpid()),"fc_hasUsrInGroup(t.agentid,{0})>0",paras.getGrpid())
                        .orderByAsc(TRecorder::getStarttime)
        );
    }

    //呼叫列表导出
    @Override
    public CmdResVo expRecordList(JSysUser user, CallReqVo paras, HttpServletResponse response)
    {
        String $usrid = user.getUsrid();
        int pagesize = paras.getPageSize();
        if (pagesize > JPubUtils.exportMaxCount) {
            paras.setPageSize(JPubUtils.exportMaxCount);
        }
        log.info("expSmsList:pagesize={}",pagesize);

        IPage<CallResvo> pages=recordList(user,paras);
        ArrayList arr=new ArrayList();

        String exptempid=JPubUtils.getExpTempID(paras.getExpfilename(),"呼叫列表数据");
        String filename=JPubUtils.getExpFileName(
                paras.getExpfilename(),exptempid
        );
        pages.convert(u->{
            HashMap map=JPubUtils.toExportMap(u);
            if(map!=null) arr.add(map);
            return u;
        });
        CmdResVo resVo=exportService.ToExcel(
                response,
                arr,
                paras.getExpidlist(),
                paras.getExpnamelist(),
                filename,
                $usrid
        );

        int okcount=resVo.getCount();
        if(okcount>0){
            FiImpAddVo addVo=new FiImpAddVo();
            addVo.setBatchid(resVo.getKeyId());
            addVo.setFilename(filename);
            addVo.setTempid(exptempid);
            addVo.setOkcount(okcount);
            String token = SpringContextUtil.getBearerToken();
            iCoreFeign.addImportHist(addVo,token);
        }
        arr.clear();

        return resVo;
    }

    @Override
    public List<DialogueResVo> quyAgentDialogue(String callid, String agentid)
    {
        return baseMapper.quyAgentDialogue(callid,agentid);
    }

    @Override
    public List<DialogueResVo> quyIvrDialogue(String callid)
    {
        return baseMapper.quyIvrDialogue(callid);
    }
}




